package org.aries.cloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.aries.cloud.lock.DistributedLock;
import org.aries.cloud.lock.LockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * TestController
 *
 * @author fcj
 * @date 2022/3/31 16:46
 */
@Slf4j
@RestController("/test")
public class TestController {

    @Autowired
    private DistributedLock redissonDistributedLock;

    @GetMapping("/lock")
    public String lock() throws Exception {
        Object lock = null;
        try {
            // 获取锁
            lock = redissonDistributedLock.tryLock("abc", 2L);
            if (lock != null) {
                TimeUnit.SECONDS.sleep(10L);
            }
        } catch (Exception e) {
            if (e instanceof LockException) {
                log.error("获取锁失败");
            }
            return "fail";
        } finally {
            // 释放锁
            redissonDistributedLock.unlock(lock);
        }
        return "success";
    }

}
